package gw.com.android.ui;

import android.os.Bundle;
import android.view.View;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

import gw.com.android.app.AppContances;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringUtils;
import www.com.library.util.UrlEncode;

/**
 * 需要单点登录的网页界面
 */
public class LoginWebFragment extends WebFragment {

    private final String TAG = "LoginWebFragment";
    private int mRgsType = AppContances.HTTP_URL_REPORT_TYPE;
    private int mSeq = 0;

    public LoginWebFragment() {

    }

    public static LoginWebFragment newInstance() {
        LoginWebFragment fragment = new LoginWebFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.i(TAG, "key = " + key);
        if (key.equals(ConfigType.DEPOSIT_TAG)) {
            mRgsType = AppContances.HTTP_URL_DEPOSIT_TYPE;
        } else if (key.equals(ConfigType.DRAW_TAG)) {
            mRgsType = AppContances.HTTP_URL_DRAW_TYPE;
        } else if (key.equals(ConfigType.REPORT_TAG)) {
            mRgsType = AppContances.HTTP_URL_REPORT_TYPE;
        } else if (key.equals(ConfigType.MY_INFO_TAG)) {
            mRgsType = AppContances.HTTP_URL_MY_INFO_TYPE;
        } else if (key.equals(ConfigType.MY_BANK_INFO_TAG)) {
            mRgsType = AppContances.HTTP_URL_MY_BANK_INFO_TYPE;
        } else if (key.equals(ConfigType.MY_UPLOAD_INFO_TAG)) {
            mRgsType = AppContances.HTTP_URL_MY_UPLOAD_INFO_TYPE;
        } else if (key.equals(ConfigType.MY_UPLOAD_DEPOSIT_FILE_TAG)) {
            mRgsType = AppContances.HTTP_URL_MY_UPLOAD_DEPOSIT_FILE_TYPE;
        } else {
            mRgsType = AppContances.HTTP_URL_GET_TOKEN_TYPE;
        }
    }

    @Override
    public void registerRxBus() {
        Disposable getTokenRegister = RxBus.getInstance().register(GTSConst.REPLY_TYPE_GET_TOKEN, Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {
                    @Override
                    public void accept(@NonNull Bundle bundle) {
                        Logger.i(TAG, "reply_type_get_token");
                        if (null != bundle) {
                            //替换token
                            if (url.contains(ConfigType.REPLACE_LOGIN_TOKEN_TAG)) {
                                String strObject = bundle.getString("strObject");
                                if (strObject == null) {
                                    strObject = "";
                                }
                                url = url.replace(ConfigType.REPLACE_LOGIN_TOKEN_TAG, strObject);
                            }
                            bundle.putString("strObject", url);
                            loadUrlView(bundle);
                        }
                    }
                });
        bindSubscription(getTokenRegister);
        Disposable getRGSRegister = RxBus.getInstance().register(GTSConst.REPLY_HTTP_RGS + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {
                    @Override
                    public void accept(@NonNull Bundle bundle) {
                        Logger.i(TAG, "reply_http_rgs");
                        if (null != bundle) {
                            loadUrlView(bundle);
                        }
                    }
                });
        bindSubscription(getRGSRegister);
    }

    @Override
    public void loadView() {
        // 未连上网络时,气泡提示
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        if (null != mErrorView) {
            mErrorView.setVisibility(View.GONE);
        }
        if (null != mProgressView) {
            mProgressView.setVisibility(View.VISIBLE);
        }
        mSeq = GTSDataListener.curSeq++;
        if (AppContances.HTTP_URL_REPORT_TYPE == mRgsType) {
            String pattener;
            if (ColorThemeUtil.instance().isGreenRise) {
                pattener = GTConfig.COLOR_GREEN_RISE;
            } else {
                pattener = GTConfig.COLOR_RED_RISE;
            }
            AppTerminal.instance().getReportSSOURL(mRgsType, mSeq, pattener, mItem.getString(ConfigType.CONFIG_TYPE_VALUE_TAG));
            Logger.i(TAG, "getReportSSOURL mRgsType = " + mRgsType + "  mSeq = " + mSeq);
        } else if (AppContances.HTTP_URL_GET_TOKEN_TYPE == mRgsType) {
            JSONObject info = new JSONObject();
            try {
                info.put("weblinkId", "ANDROID_DEPOSITE");
                info.put("fromURL", "ANDROID");
                info.put("toURL", url);
                if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
                    info.put("TokenEmpty", 1);
                }
                GTSDataListener.instance().addSeqList(mSeq + "", AppContances.NORMALREQ_TYPE_GET_TOKEN);
                AppTerminal.instance().NormalReqConfigSvr(ConfigType.HTTP_GET_TOKEN_TAG, info.toString(), mSeq);
                Logger.i(TAG, "NormalReqConfigSvr mRgsType = " + mRgsType + "  mSeq = " + mSeq);
            } catch (JSONException e) {
                Logger.e(TAG, e);
            }
        } else {
            AppTerminal.instance().getSSOURL(mRgsType, mSeq);
            Logger.i(TAG, "getSSOURL mRgsType = " + mRgsType + "  mSeq = " + mSeq);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 根据返回的url地址加载界面
     */
    public void loadUrlView(Bundle bundle) {
        int iValue = bundle.getInt("iValue");
        if (iValue == 0 && mSeq == bundle.getInt("iNotification")) {
            String rgsUrl = bundle.getString("strObject");
            Logger.i(TAG, "loadUrlView rgsUrl = " + rgsUrl);
            if (null != mWebView && null != rgsUrl && rgsUrl.length() > 0) {
                url = rgsUrl;
                if (null != mErrorView) {
                    mErrorView.setVisibility(View.GONE);
                }
                initTimerTask();
                if (url.contains("service=")) {
                    String serviceURL = url.substring(url.indexOf("service="));
                    if (!StringUtils.isEmpty(serviceURL) && serviceURL.contains("?")) {
                        url = url + UrlEncode.encode("&deviceId=" + DeviceUtil.instance().getMacAddr(getActivity()) + "&AccountSessionID=" + GTConfig.instance().mSession + "&terminal=android&version=" + BuildConfig.VERSION_CODE);
                    } else {// 不要问我为什么要这么改，我只知道这么改，app表现就正常，网页能正常打开,上面的逻辑可能是在某种特殊情况才会用到，不过目前我没遇到，所以我也不知道到底发生了什么，就这样
                        url = url + "&" + UrlEncode.encode("deviceId=" + DeviceUtil.instance().getMacAddr(getActivity()) + "&AccountSessionID=" + GTConfig.instance().mSession + "&terminal=android&version=" + BuildConfig.VERSION_CODE);
                    }
                }
                Logger.i(TAG, "load url = " + url);
                mWebView.loadUrl(url);
                mWebView.setVisibility(View.VISIBLE);
            }
        } else {
            Logger.i(TAG, "an error occured,iValue = " + iValue);
            if (iValue == 1326) {
                mWebView.setVisibility(View.GONE);
                mProgressView.setVisibility(View.GONE);
                mErrorView.setVisibility(View.GONE);
                mAccountLockingView.setVisibility(View.VISIBLE);
            } else {
                if (isResumed() && !isHidden() && getActivity() != null) {
                    showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
                }
                mWebView.setVisibility(View.GONE);
                mProgressView.setVisibility(View.GONE);
                mErrorView.setVisibility(View.VISIBLE);
            }

        }
    }
}
